import nodemailer from 'nodemailer'
import { CacheState, SendEmailCheck } from './expireCheck'

const config = {
    coolingTime: 1,
    expirationTime: 5
}

const sendEmailCheck = new SendEmailCheck(config.expirationTime * 1000 * 60, config.coolingTime * 1000 * 60)

const verificationCode = (toEmail: string, code: string) => sendEmailCheck.checkCode(toEmail, code)

// 发送邮件
const sendMail = (toEmail: string) => {
    return new Promise<void>((resolve, reject) => {
        if (sendEmailCheck.checkCooling(toEmail) === CacheState.unexpired) return reject('请勿频繁请求')
        const code = String(Math.floor(100000 + Math.random() * 900000))
        sendEmailCheck.add({
            toEmail,
            code
        })
        nodemailer.createTransport({
            // host: 'smtp.qq.com', // 主机
            // secureConnection: true, // 使用 SSL
            service: 'qq',
            port: 465, // SMTP 端口
            auth: {
                user: '1548720321@qq.com',    // 账号
                pass: 'pxrzsdynjlkbhahh' // 授权码
            }
        }).sendMail({
            from: '1548720321@qq.com',
            to: toEmail,
            subject: '【仓库管理系统】验证码',
            html: `
                <div class="container" style="width: 100%; height: 200px; display: flex; justify-content: center; align-items: center;">
                    <span>【仓库管理系统】验证码：<b>${code}</b>，验证码${config.expirationTime}分钟后失效，请勿告诉他人</span>
                </div>
            `
        }, (err) => {
            if (err) return reject(err)
            resolve()
        })
    })
}

export {
    sendMail,
    verificationCode
}